package com.lsz.flight_system.service.Impl;

import com.lsz.flight_system.entity.BuyTicketsMessage;
import com.lsz.flight_system.entity.PlaneMessage;
import com.lsz.flight_system.entity.UserMessage;
import com.lsz.flight_system.repository.BuyTicketsMessageRepository;
import com.lsz.flight_system.repository.PlaneMessageRepository;
import com.lsz.flight_system.repository.UserMessageRepository;
import com.lsz.flight_system.service.BuyTicketsMessageService;
import com.lsz.flight_system.service.PlaneMessageService;
import com.lsz.flight_system.service.UserMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BuyTicketsMessageServiceImpl implements BuyTicketsMessageService {

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    PlaneMessageRepository planeMessageRepository;

    @Autowired
    BuyTicketsMessageRepository buyTicketsMessageRepository;

    @Autowired
    UserMessageRepository userMessageRepository;

    @Override
    public BuyTicketsMessage getBuyTicketsMessage(UserMessage userMessage, PlaneMessage planeMessage) {
        BuyTicketsMessage buyTicketsMessage = new BuyTicketsMessage();
        buyTicketsMessage.setUsername(userMessage.getUsername());
        buyTicketsMessage.setPhone(userMessage.getPhone());
        buyTicketsMessage.setPlaneId(planeMessage.getPlaneId());
        buyTicketsMessage.setBuyTime(LocalDateTime.now());
        buyTicketsMessage.setTicketState("售出");
        buyTicketsMessage.setPlaneRoute(planeMessage.getPlaneRoute());
//        buyTicketsMessage.setUpdateTime(LocalDateTime.now());
        return buyTicketsMessage;
    }

    @Override
    //保存购票信息
    public Boolean addBuyTicketsMessage(BuyTicketsMessage buyTicketsMessage) {
        if (buyTicketsMessage == null) {
            return false;
        }
        buyTicketsMessageRepository.save(buyTicketsMessage);
        return true;
    }

    @Override
    //更新余额
    public boolean updateUserBalance(String username, Float balance) {
        UserMessage userMessage = userMessageService.getUserMessageByUsername(username);
        userMessage.setBalance(balance);
        userMessageRepository.save(userMessage);
        return true;
    }

    @Override
    public List<BuyTicketsMessage> getUserBuyTicketsMessages(Map<String,Object> map) {
        return buyTicketsMessageRepository.findAll(new Specification<BuyTicketsMessage>() {
            @Override
            public Predicate toPredicate(Root<BuyTicketsMessage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<>();
                if (map.containsKey("username") && !StringUtils.isEmpty(map.get("username"))){
                    predicateList
                            .add(cb.equal(root.get("username").as(String.class),map.get("username")));
                }
                Predicate[] predicateArr = new Predicate[predicateList.size()];
                return cb.and(predicateList.toArray(predicateArr));
            }
        });
    }

    @Override
    public boolean userBackTickets(Long id) {
        BuyTicketsMessage buyTicketsMessage = buyTicketsMessageRepository.findBuyTicketsMessageById(id);
//        UserMessage userMessage = userMessageService.getUserMessageByUsername(buyTicketsMessage.getUsername());
        PlaneMessage planeMessage = planeMessageRepository.findPlaneMessageByPlaneId(buyTicketsMessage.getPlaneId());
        try {
            //调用UserMessageService中的充值接口，将退票金额存入余额中
            userMessageService.userRecharge(buyTicketsMessage.getUsername(), planeMessage.getTicketPrice());
            //增加飞机余票并判断，若为无票修改状态
            planeMessage.setRemainTicket(planeMessage.getRemainTicket()+1);
            planeMessage.setPlaneState("售票");
            planeMessageRepository.save(planeMessage);
            //删除用户购票信息
            buyTicketsMessageRepository.deleteById(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public BuyTicketsMessage findBuyTicketsMessageById(Long id) {
        return buyTicketsMessageRepository.findBuyTicketsMessageById(id);
    }

    @Override
    public List<BuyTicketsMessage> findAllBuyTicketsMessage(Map<String, Object> map) {
        return buyTicketsMessageRepository.findAll(new Specification<BuyTicketsMessage>() {
            @Override
            public Predicate toPredicate(Root<BuyTicketsMessage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<>();

                if (map.containsKey("planeId") && !StringUtils.isEmpty(map.get("planeId"))){
                    predicateList
                            .add(cb.equal(root.get("planeId").as(String.class),map.get("planeId")));
                }
                //模糊查询
                if (map.containsKey("username") && !StringUtils.isEmpty(map.get("username"))){
                    predicateList
                            .add(cb.like(root.get("username"),"%"+map.get("username").toString()+"%"));
                }

                Predicate[] predicateArr = new Predicate[predicateList.size()];
                return cb.and(predicateList.toArray(predicateArr));
            }
        });
    }

    @Override
    public boolean delBuyTicketsMessage(Long id) {
        try {
            buyTicketsMessageRepository.deleteById(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateUserBuyTicketStart(Long id, String ticketState) {
        BuyTicketsMessage buyTicketsMessage = buyTicketsMessageRepository.findBuyTicketsMessageById(id);
        try {
            buyTicketsMessage.setTicketState(ticketState);
            buyTicketsMessageRepository.save(buyTicketsMessage);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

}
